<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Menu;
use App\Models\Role;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Support\Facades\Hash;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;

class AuthController extends Controller
{
    public function init()
    {

        $user =  User::where('username', 'admin')->first();

        if ($user) {
            return $this->success(data: [
                'message' => '初始化成功',
            ]);
        }

        try {
            $result = User::create([
                'username' => 'admin',
                'password' => Hash::driver('bcrypt')->make('123456')
            ]);
            return $this->success(data: [
                'message' => '初始化成功',
                'id'      =>  $result->id,
            ]);
        } catch (HttpException $error) {
            return $this->error(status: 500, data: $error);
        }
    }

    public function login(Request $request)
    {
        $body = $request->json()->all();

        $user = User::where('username', $body['username'])->first();

        if (!$user) {
            return $this->error(data: [
                'message'  => '用户不存在'
            ], code: 403);
        }

        $isLogin = Hash::check($body['password'], $user->password);

        if (!$isLogin) {
            return $this->error(data: [
                'message' => '账号或密码错误'
            ], code: 403);
        }

        $token = JWTAuth::fromUser($user);

        return $this->success(data: [
            'accessToken' => $token,
            'refreshToken'  => $token
        ], isObject: true);
    }


    public function info()
    {
        $user = JWTAuth::user();

        $username = $user['username'];

        $menus = [];

        if (strtolower($username) === 'admin') {
            $menuModel = Menu::whereNot('type', 'FEATURE')->get()->toArray();
            $menus = buildTreeWithoutIds($menuModel);
        } else {
            $roles = array_map('intval', explode(',', $user->roles));

            $roleList = Role::whereIn('id', $roles)->get()->toArray();
            $menuModel = Menu::whereIn('id', processMenuPermissions($roleList))->whereNot('type', 'FEATURE')->get()->toArray();
            $menus = buildTreeWithoutIds($menuModel);
        }

        $data = array_merge($user->toArray(), ['menus' => $menus]);

        $data = array_merge($data, [
            'menuPermissions' => ["*"],
            'apiPermissions' => ["*"],
            'featurePermissions' => ["*"]
        ]);

        return $this->success(data: $data, isObject: true);
    }

    public function logout()
    {
        try {
            JWTAuth::invalidate(JWTAuth::getToken());
            return $this->success(data: [
                'message' => '退出成功'
            ]);
        } catch (JWTException $e) {
            return $this->error(status: 500, data: [
                'message' => '退出失败，请稍后再试',
                'error'   => $e->getMessage()
            ]);
        }
    }
}
